package problem56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//56.合并区间
//https://leetcode.cn/problems/merge-intervals/

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a, b)->{
            return a[0] - b[0];
        });

        List<int[]> list = new ArrayList<>();
        int i = 0;
        int n = intervals.length;
        int begin = 0,end = 0;

        while(i < n) {
            begin = intervals[i][0];
            end = intervals[i][1];
            while(i < n - 1 && intervals[i+1][0] <= end) {
                end = Math.max(end, intervals[i+1][1]);
                i++;
            }
            list.add(new int[]{begin, end});
            i++;
        }

        return list.toArray(new int[0][]);
    }
}